package com.LeeCode;

import java.util.HashSet;
import java.util.Set;

/**
 * 有效的数独
 */

public class Code036 {
    public static void main(String[] args) {

    }

    public boolean isValidSudoku(char[][] board) {
        int row = board.length, col = board[0].length;
        HashSet<Character> set = new HashSet<>();

        // 检查每一行
        for (int i = 0; i < row; i++) {
            set.clear();
            for (int j = 0; j < col; j++) {
                if (board[i][j] != '.') {
                    if (!set.contains(board[i][j])) {
                        set.add(board[i][j]);
                    } else {
                        return false;
                    }
                }
            }
        }

        // 检查每一列
        for (int j = 0; j < col; j++) {
            set.clear();
            for (int i = 0; i < row; i++) {
                if (board[i][j] != '.') {
                    if (!set.contains(board[i][j])) {
                        set.add(board[i][j]);
                    } else {
                        return false;
                    }
                }
            }
        }
        // 检查每个小宫格
        for (int i = 0; i < 9; i = i + 3) {
            for (int j = 0; j < 9; j = j + 3) {
                set.clear();
                for (int index = 0; index < 9; index++) {
                    int x = index / 3, y = index % 3;
                    if (board[i + x][j + y] != '.') {
                        if (!set.contains(board[i + x][j + y])) {
                            set.add(board[i + x][j + y]);
                        } else {
                            return false;
                        }
                    }
                }
            }
        }

        return true;
    }

    public boolean isValidSudoku1(char[][] board) {
        Set<String> seen = new HashSet<>();
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.') {
                    // 为每个数字生成唯一标识
                    String rowKey = c + " in row " + i;
                    String colKey = c + " in col " + j;
                    String boxKey = c + " in box " + i/3 + "-" + j/3;

                    if (!seen.add(rowKey) || !seen.add(colKey) || !seen.add(boxKey)) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
